package xyj.sparrow.scheduler.server.connect;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.x.discovery.ServiceInstance;
import xyj.sparrow.common.connect.SparrowConnect;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author 江南小俊
 * @since 2021/6/25 下午10:51
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class ConnectConsumer implements Consumer<List<ServiceInstance<Object>>> {
    private CopyOnWriteArrayList<SparrowConnect> sparrowConnects;

    @Override
    public void accept(List<ServiceInstance<Object>> serviceInstances) {
        log.info("accept:{}", serviceInstances.size());

        Map<String, SparrowConnect> connectMap =
                sparrowConnects.stream().collect(Collectors.toMap(c -> c.getConnectDesc(), c -> c));

        //处理分片参数
        for (int i = 0; i < serviceInstances.size(); i++) {
            String key = serviceInstances.get(i).getAddress() + ":" + serviceInstances.get(i).getPort();
            if (connectMap.containsKey(key)) {
                connectMap.get(key).setConnectIndex(i + 1);
                connectMap.get(key).setConnectTotal(serviceInstances.size());
            }
        }

    }
}
